local skynet = require "skynet"
local filelog = require "filelog"
local msghelper = require "agenthelper"
local playerdatadao = require "playerdatadao"
local configdao = require "configdao"
local table = table
require "enum"

local  UpdateInvitecode = {}

--[[
//请求更新邀请吗
message UpdateInvitecodeReq {
	optional Version version = 1;
	optional string invitecode = 2;
}

message UpdateInvitecodeRes {
	optional int32 errcode = 1; //错误原因 0表示成功
	optional string errcodedes = 2; // 错误描述
	optional string invitecode = 3; 	
}
]]

function  UpdateInvitecode.process(session, source, fd, request)
	local responsemsg = {
		errcode = EErrCode.ERR_SUCCESS,
	}
	local server = msghelper:get_server()

	--检查当前登陆状态
	if not msghelper:is_login_success() then
		filelog.sys_warning("UpdateInvitecode.process invalid server state", server.state)
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "无效的请求!"
		msghelper:send_resmsgto_client(fd, "UpdateInvitecodeRes", responsemsg)		
		return
	end

	if request == nil 
		or request.invitecode == nil 
		or request.invitecode == "" then
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "无效的请求参数!"
		msghelper:send_resmsgto_client(fd, "UpdateInvitecodeRes", responsemsg)		
		return		
	end

	if server.info.invitecode ~= nil and server.info.invitecode ~= "" then
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "您已经绑定过邀请码:"..server.info.invitecode
		responsemsg.invitecode = server.info.invitecode
		msghelper:send_resmsgto_client(fd, "UpdateInvitecodeRes", responsemsg)		
		return				
	end

	local status, invite_rid = pcall(tonumber, request.invitecode)
	if not status or invite_rid == nil or invite_rid == server.rid then
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "邀请码格式不正确:"..server.info.invitecode
		responsemsg.invitecode = server.info.invitecode
		msghelper:send_resmsgto_client(fd, "UpdateInvitecodeRes", responsemsg)		
		return						
	end

	if not playerdatadao.is_player_exist(invite_rid) then
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "邀请码不存在:"..server.info.invitecode
		responsemsg.invitecode = server.info.invitecode
		msghelper:send_resmsgto_client(fd, "UpdateInvitecodeRes", responsemsg)		
		return								
	end

	server.info.invitecode = request.invitecode

	playerdatadao.save_player_info("update", server.rid, server.info)
	
	responsemsg.invitecode = server.info.invitecode
	
	msghelper:send_resmsgto_client(fd, "UpdateInvitecodeRes", responsemsg)

	--赠送玩家8个金豆
	local bind_awardgemstone_num = configdao.get_businessconfitem_by_index(100, 1000, "globalvarcfg", "bind_awardgemstone_num")
	msghelper:save_player_gemstone(server.rid, bind_awardgemstone_num, EReasonChangeCurrency.CHANGE_CURRENCY_BINDA_INVITECODE_AWARD, "invitecode")
	msghelper:send_gemstonechange_notice()
end

return UpdateInvitecode